package org.pluslibs.framework.swingplus.model;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;

import javax.swing.JComboBox;
import javax.swing.text.JTextComponent;

import org.apache.commons.lang.StringUtils;

public abstract class AbstractModel<T extends ModelDataEnumInterface> extends Observable {
    private final Map<T, String> fields = new HashMap<T, String>();

    public String get(T key) {
        return fields.get(key);
    }

    public void put(T key, String value) {
        fields.put(key, value);
    }

    public void mapFieldToModel(JTextComponent field, final T key) {
        field.addKeyListener(implementFieldToModelKeyListener(field, key));
    }

    public void mapFieldToModel(JComboBox field, final T key) {
        field.addItemListener(implementFieldToModelItemListener(key));
    }

    private ItemListener implementFieldToModelItemListener(final T key) {
        return new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                put(key, e.getItem().toString());
            }
        };
    }

    private KeyListener implementFieldToModelKeyListener(final JTextComponent field, final T key) {
        return new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {}

            @Override
            public void keyReleased(KeyEvent e) {
                put(key, field.getText());
            }

            @Override
            public void keyPressed(KeyEvent e) {}
        };
    }

    @Override
    public String toString() {
        return fields.toString();
    }

    public String[] validateRequiredFields(ModelDataEnumInterface[] enums) {
        List<String> results = new ArrayList<String>();
        for (ModelDataEnumInterface t : enums) {
            if (t.isRequiredField() && StringUtils.isBlank(fields.get(t))) {
                results.add(t.toString());
            }
        }
        return results.toArray(new String[results.size()]);
    }
}
